package com.ydgk.dao;

import com.ydgk.db.JDBCUtils;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public abstract class BaseDao<T> {
    //第页分5条
    public int pageCount = 8 ;
    //1. 获取JDBCTemplate对象
    protected JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    public abstract int save(T t);

    public abstract int updateById(T t);

    public abstract int deleteById(int id);

    public abstract List<T> findAll();

    public abstract T findById(int id);

    public abstract List<T> paging(int pageNumber);

    public int maxPage(String tableName){
        String sql = "select count(*) from "+tableName;
        long t = template.queryForObject(sql, Long.class);
        int total = (int)t;//将long类型转换成int类型
        return total % pageCount == 0 ? total / pageCount : total / pageCount + 1 ;
    }

    /**
     * //处理分页的方法
     * @param targetUrl    服务器地址
     * @param maxPage   总页数
     * @param pageNumber 当前页
     * @param param       参数
     * @return
     */
    public String genPagination(String targetUrl, long maxPage,int pageNumber, String param) {
        StringBuilder pageCode = new StringBuilder();
        if (maxPage == 0) {
            return "未查询到数据";
        } else {
            pageCode.append("<ul class='pagination'>");
            if (pageNumber == 1) {
                pageCode.append("<li class='disabled'><a>首页</a></li>");
                pageCode.append("<li class='disabled'><a>上一页</a></li>");
            } else {
                pageCode.append("<li><a href='" + targetUrl + "?pageNumber=1&"
                        + param + "'>首页</a></li>");
                pageCode.append("<li><a href='" + targetUrl + "?pageNumber="
                        + (pageNumber - 1) + "&" + param + "'>上一页</a></li>");
            }
            for (int i = pageNumber - 2; i <= pageNumber + 2; i++) {
                if (i < 1 || i > maxPage) {
                    continue;
                }
                if (i == pageNumber) {
                    pageCode.append("<li class='active'><a>" + i + "</a></li>");
                } else {
                    pageCode.append("<li><a href='" + targetUrl + "?pageNumber=" + i
                            + "&" + param + "'>" + i + "</a></li>");
                }
            }
            if (pageNumber == maxPage) {
                pageCode.append("<li class='disabled'><a>下一页</a></li>");
                pageCode.append("<li class='disabled'><a>尾页</a></li>");
            } else {
                pageCode.append("<li><a href='" + targetUrl + "?pageNumber="
                        + (pageNumber + 1) + "&" + param + "'>下一页</a></li>");
                pageCode.append("<li><a href='" + targetUrl + "?pageNumber="
                        + maxPage + "&" + param + "'>尾页</a></li>");
            }
            pageCode.append("</ul>");
        }
        return pageCode.toString();
    }
}
